import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

import { QueryDTO } from '../dto/query.dto';

@Injectable()
export class QueryPipe implements PipeTransform<QueryDTO, QueryDTO> {
  transform(
    { sortOrder, sortName, orderBy, ...data }: QueryDTO,
    metadata: ArgumentMetadata,
  ): QueryDTO {
    const order =
      (sortOrder && sortOrder.toLowerCase().includes('asc') && 'ASC') || 'DESC';
    orderBy = sortOrder && sortName && `${sortName}_${order}`;
    return {
      ...data,
      sortOrder: order,
      orderBy,
      sortName,
    };
  }
}
